<template>
  <div class="mb-5">
    <div class="flex items-center mb-3">
      <img :src="socBatteryIcon" alt="soc-battery" class="w-6 h-6 mr-2" />
      <h3 class="text-lg font-medium">SOC (%)</h3>
    </div>

    <!-- SOC图表 -->
    <div class="soc-chart-container">
      <div ref="socChartRef" class="chart-container" style="height: 300px"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, markRaw, nextTick, watch, computed } from "vue";
import { batteryData } from "../../data";
import * as echarts from "echarts/core";
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from "echarts/components";
import { LineChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import socBatteryIcon from "./assets/soc-battery.png";

// 组件props
interface Props {
  processedData?: any;
  isLoading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  isLoading: false
});

// 注册 ECharts 组件
echarts.use([TitleComponent, TooltipComponent, LegendComponent, GridComponent, LineChart, CanvasRenderer]);

const socChartRef = ref(null);
let socChart: any = null;

// 创建SOC图表配置
const createSOCChartOption = () => {
  let chartData: number[] = [];
  let timePoints: string[] = [];

  if (props.processedData && props.processedData.socList) {
    // 使用真实数据 - 将电池数据转换为SOC百分比
    chartData = props.processedData.socList.map((value: number) => Math.min(Math.max(value, 0), 100));
    timePoints = props.processedData.timePoints;
    console.log("SOCCard 使用真实数据:", {
      chartData: chartData?.slice(0, 5),
      timePoints: timePoints?.slice(0, 5),
      dataLength: chartData?.length
    });
  } else {
    // 使用mock数据
    chartData = batteryData.socData.yAxis;
    timePoints = batteryData.socData.xAxis;
    console.log("SOCCard 使用mock数据:", {
      chartData: chartData?.slice(0, 5),
      timePoints: timePoints?.slice(0, 5)
    });
  }

  return {
    grid: {
      left: "3%",
      right: "4%",
      bottom: "10%",
      top: "5%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params: any) {
        const data = params[0];
        return `${data.name}<br/>SOC: ${data.value}%`;
      }
    },
    xAxis: {
      type: "category",
      data: timePoints,
      axisLabel: {
        formatter: "{value}",
        fontSize: 12,
        color: "#333"
      },
      axisLine: {
        lineStyle: {
          color: "#E0E0E0"
        }
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: "value",
      name: "SOC (%)",
      min: 0,
      max: 100,
      axisLabel: {
        formatter: "{value}%",
        fontSize: 12,
        color: "#333"
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: "#F0F0F0",
          type: "dashed"
        }
      }
    },
    series: [
      {
        name: "SOC",
        type: "line",
        data: chartData,
        smooth: true,
        symbol: "circle",
        symbolSize: 6,
        lineStyle: {
          color: "#00D4AA",
          width: 3
        },
        itemStyle: {
          color: "#00D4AA",
          borderColor: "#fff",
          borderWidth: 2
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(0, 212, 170, 0.3)"
              },
              {
                offset: 1,
                color: "rgba(0, 212, 170, 0.1)"
              }
            ]
          }
        }
      }
    ]
  };
};

// 更新图表
const updateChart = () => {
  if (socChart) {
    socChart.setOption(createSOCChartOption(), true);
  }
};

const initSOCChart = () => {
  if (socChartRef.value) {
    socChart = markRaw(echarts.init(socChartRef.value));
    socChart.setOption(createSOCChartOption());

    window.addEventListener("resize", () => {
      socChart?.resize();
    });
  }
};

// 添加props监听
watch(
  [() => props.processedData],
  () => {
    console.log("SOCCard 监听到props变化:", {
      hasProcessedData: !!props.processedData,
      socListLength: props.processedData?.socList?.length
    });

    if (props.processedData && props.processedData.socList) {
      nextTick(() => {
        console.log("SOCCard 开始更新图表");
        updateChart();
      });
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  nextTick(() => {
    initSOCChart();
  });
});

// 暴露更新方法
defineExpose({
  updateChart
});
</script>

<style scoped>
.chart-container {
  width: 100%;
}

.soc-chart-container {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
}
</style>
